package com.wwwarehouse.usercenter.fragment.register;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.wwwarehouse.common.BuildConfig;
import com.wwwarehouse.common.bean.upload.FileUploadBean;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.http.NetUtils;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.BitmapUtil;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.FileUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PermissionUtils;
import com.wwwarehouse.common.tripartite_widget.faceprint.FaceUtil;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.common.UserCenterCommon;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * 实名认证
 * Created by xiaoke.ni on 2017/8/11.
 */
public class RCRealNameAuthStep1Fragment extends RegisterCardBaseFragment implements View.OnClickListener, PermissionUtils.PermissionCallbacks {
    private View mRootView;

    private ImageView mIdCardFrontLayout;
    private ImageView mIdCardBackLayout;
    private Button    mNextBtn;

    private FileUtils mFileUtils;

    private final String mFrontPhotoName     = "frontPhoto.jpg";
    private final String mFrontPartPhotoName = "frontPartPhoto.jpg";
    private final String mBackPhotoName      = "backPhoto.jpg";

    private int mCurrentPhoto;  // 1表示正面 2 表示反面

    private File mFrontPhotoFile;
    private File mBackPhotoFile;
    private File mCutHead;
    private boolean mIsFrontPhotoToken;
    private boolean mIsBackPhotoToken;

    private static final int REQUEST_CODE_CAPTURE_FRONT = 1;
    private static final int REQUEST_CODE_CAPTURE_BACK  = 2;
    private static final int REQUEST_CROP_IMAGE         = 3;


    public static final int CAPTURE_FRONT_PERMISSION_CODE = 0;
    public static final int CAPTURE_BACK_PERMISSION_CODE  = 1;

    private List mFrontList;
    private List mBackList;

    private boolean mIsFirst   = true;
    private boolean mIsCutHead = true;
    private LinearLayout mLlFrontNo;
    private LinearLayout mLlBackNo;
    private Intent mIntent;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_rc_real_name_auth_step1, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    private void initView() {
        mIdCardFrontLayout = findView(mRootView, R.id.ll_id_card_front);
        mLlFrontNo = findView(mRootView, R.id.ll_front_no);
        mIdCardBackLayout = findView(mRootView, R.id.ll_id_card_back);
        mLlBackNo = findView(mRootView, R.id.ll_back_no);
        mNextBtn = findView(mRootView, R.id.next_btn);
        if (UserCenterCommon.getInstance().getFrontPhotoFile() != null) {
            mIsFrontPhotoToken = true;
            mFrontPhotoFile = UserCenterCommon.getInstance().getFrontPhotoFile();
            processPhoto(mFrontPhotoFile, mIdCardFrontLayout);
        }
        if (UserCenterCommon.getInstance().getBackPhotoFile() != null) {
            mIsBackPhotoToken = true;
            mBackPhotoFile = UserCenterCommon.getInstance().getBackPhotoFile();
            processPhoto(mBackPhotoFile, mIdCardBackLayout);
        }
        if (UserCenterCommon.getInstance().getCutHead() != null) {
            fileSrc = UserCenterCommon.getInstance().getCutHead();
            cutHeadlist.add(fileSrc);
        }
        mFileUtils = new FileUtils();
    }

    private void initEvent() {
        mIdCardFrontLayout.setOnClickListener(this);
        mIdCardBackLayout.setOnClickListener(this);
        mNextBtn.setOnClickListener(this);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof RCRealNameAuthStep1Fragment) {
            mActivity.setTitle(R.string.real_name_auth);
        }
    }

    @Override
    public void requestDatas() {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.ll_id_card_front) {
            mIsCutHead = true;//防止接口的乱入
            mCurrentPhoto = 1;
            PermissionUtils.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAPTURE_FRONT_PERMISSION_CODE);

        } else if (i == R.id.ll_id_card_back) {
            mCurrentPhoto = 2;
            PermissionUtils.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAPTURE_BACK_PERMISSION_CODE);

        } else if (i == R.id.next_btn) {
            mFrontList = new ArrayList<>();
            mBackList = new ArrayList<>();
            mFrontList.add(mFrontPhotoFile.getAbsolutePath());
            mBackList.add(mBackPhotoFile.getAbsolutePath());

            if (NetUtils.isHttpConnected(mActivity)) {
                if (cutHeadlist.size() == 0) {
                    Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.img_head);
                    if (mCutHead == null) {
                        mCutHead = mFileUtils.getImagesFile("cut_head.jpg");
                    }
                    try {
                        FileOutputStream out = new FileOutputStream(mCutHead);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                        out.flush();
                        out.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    cutHeadlist.add(mCutHead.getAbsolutePath());
                    UserCenterCommon.getInstance().setCutHead(mCutHead.getAbsolutePath());
                }
                uploadPhoto(cutHeadlist, Constant.URL_UPLOADS_AVATAR);
            } else {
                toast(mActivity.getResources().getString(R.string.no_net));
            }


        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (perms.size() == 3) {
            switch (requestCode) {
                case CAPTURE_FRONT_PERMISSION_CODE:
                    takePhoto(mFrontPhotoName);
                    Constant.isTakePhotoFinished = false;
                    break;
                case CAPTURE_BACK_PERMISSION_CODE:
                    takePhoto(mBackPhotoName);
                    Constant.isTakePhotoFinished = false;
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        PermissionUtils.permissionDialog(mActivity, perms, null);
    }

    private void takePhoto(String photoName) {
        mIntent = new Intent();
        mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri;
        if (mCurrentPhoto == 1) {
            if (mFrontPhotoFile == null) {
                mFrontPhotoFile = mFileUtils.getImagesFile(photoName);
            }
            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileProvider", mFrontPhotoFile);
                mIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(mIntent, REQUEST_CODE_CAPTURE_FRONT);
            } else {
                uri = Uri.fromFile(mFrontPhotoFile);
                mIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);  //存储拍照的位置
                startActivityForResult(mIntent, REQUEST_CODE_CAPTURE_FRONT); //开启照相机界面
            }
        } else if (mCurrentPhoto == 2) {
            if (mBackPhotoFile == null) {
                mBackPhotoFile = mFileUtils.getImagesFile(photoName);
            }

            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileProvider", mBackPhotoFile);
                mIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(mIntent, REQUEST_CODE_CAPTURE_BACK);
            } else {
                uri = Uri.fromFile(mBackPhotoFile);
                mIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(mIntent, REQUEST_CODE_CAPTURE_BACK);
            }
        }
    }

    String fileSrc = null;
    private List<String> cutHeadlist = new ArrayList();
    private Uri mUri;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_CAPTURE_FRONT:

                    processPhoto(mFrontPhotoFile, mIdCardFrontLayout);
                    UserCenterCommon.getInstance().setFrontPhotoFile(mFrontPhotoFile);


                    try {
                        updateGallery(mFrontPhotoFile.getAbsolutePath());
                        // 跳转到图片裁剪页面
                        //判断是否是AndroidN以及更高的版本
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            mUri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".fileProvider", new File(mFrontPhotoFile.getAbsolutePath()));
                        } else {
                            mUri = Uri.fromFile(new File(mFrontPhotoFile.getAbsolutePath()));
                        }
                        FaceUtil.cropPicture(this, mUri);
                    } catch (Exception e) {
                        LogUtils.showLog("Exception" + e.toString());
                    }
                    break;
                case REQUEST_CROP_IMAGE:
                    try {
                        Constant.isTakePhotoFinished = false;
                        // 获取返回数据
                        Bitmap bmp = data.getParcelableExtra("data");
                        // 若返回数据不为null，保存至本地，防止裁剪时未能正常保存
                        if (null != bmp) {
                            FaceUtil.saveBitmapToFile(mActivity, bmp);
                        }
                        if (!TextUtils.isEmpty(FaceUtil.getImagePath(mActivity, "press_result.jpg").getAbsolutePath())) {
                            // 获取图片保存路径
                            fileSrc = FaceUtil.getImagePath(mActivity, "press_result.jpg").getAbsolutePath();
                            cutHeadlist.add(fileSrc);
                            UserCenterCommon.getInstance().setCutHead(fileSrc);
                        } else {
                            //                            cutHeadlist.add(mFrontPhotoFile.getAbsolutePath());
                            //                            UserCenterCommon.getInstance().setCutHead(mFrontPhotoFile.getAbsolutePath());
                        }

                    } catch (Exception e) {
                        LogUtils.showLog(e.toString());
                    }



                    break;
                case REQUEST_CODE_CAPTURE_BACK:

                    processPhoto(mBackPhotoFile, mIdCardBackLayout);
                    UserCenterCommon.getInstance().setBackPhotoFile(mBackPhotoFile);
                    break;
                default:
                    break;
            }
        }
    }

    private void updateGallery(String filename) {
        MediaScannerConnection.scanFile(mActivity, new String[]{filename}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {

                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();

        Constant.isTakePhotoFinished = true;


    }

    private void processPhoto(File photoFile, ImageView imageView) {
        Bitmap bitmap = getSmallBitmap(photoFile.getPath());
        int degree = BitmapUtil.getBitmapDegree(photoFile.getPath());
        Bitmap rotatedBitmap = BitmapUtil.rotateBitmapByDegree(bitmap, degree);
        //        linearLayout.setBackground(new BitmapDrawable(rotatedBitmap));
        imageView.setImageBitmap(rotatedBitmap);
        try {
            FileOutputStream fos = new FileOutputStream(photoFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mCurrentPhoto == 1) {
            mIsFrontPhotoToken = true;
        } else if (mCurrentPhoto == 2) {
            mIsBackPhotoToken = true;
        }

        if (mIsFrontPhotoToken) {
            mLlFrontNo.setVisibility(View.INVISIBLE);
        }

        if (mIsBackPhotoToken) {
            mLlBackNo.setVisibility(View.INVISIBLE);
        }
        if (mIsBackPhotoToken && mIsFrontPhotoToken) {
            mNextBtn.setEnabled(true);
            mNextBtn.setBackgroundResource(R.drawable.common_btn2_solid_selector);
        }
    }

    private static Bitmap getSmallBitmap(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = BitmapUtil.calculateInSampleSize(options, 800, 800);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    //上传身份证图片
    private void uploadPhoto(List<String> list, String url) {

        if (mIsCutHead) {

            showProgressDialog("0%");
        }
        NoHttpUtils.httpUploadFileRequest(url, list, new NoHttpUtils.OnFileUploadListener() {


            @Override
            public void onStart(int what) {

            }

            @Override
            public void onCancel(int what) {
            }

            @Override
            public void onProgress(int what, int progress) {
                if (mIsCutHead) {
                    int i = progress / 100 * 30;
                    setProgressDialogText(i + "%");
                } else if (mIsFirst && !mIsCutHead) {

                    int i = progress / 100 * 40 + 30;
                    setProgressDialogText(i + "%");
                } else if (!mIsFirst && !mIsCutHead) {
                    int i = progress / 100 * 30 + 70;
                    setProgressDialogText(i + "%");
                }
            }

            @Override
            public void onFinish(int what) {
                LogUtils.showInfoLog("onFinish" + what);
            }

            @Override
            public void onError(int what, Exception exception) {
                LogUtils.showInfoLog("onError" + what + exception.toString());
            }
        }, new NoHttpUtils.OnFileUploadResultListener() {
            @Override
            public void onSucceed(int what, FileUploadBean fileUploadBean) {

                if ("0".equals(fileUploadBean.getCode())) {
                    List<FileUploadBean.DataBean> data = fileUploadBean.getData();
                    if (data.size() > 0) {
                        if (mIsFirst && !mIsCutHead) {//因为两个接口接着调用 用于区分是第几个借口

                            if (data.get(0).getIdcard() != null) {
                                UserCenterCommon.getInstance().setBirthPlace(data.get(0).getIdcard().getNplace());
                                UserCenterCommon.getInstance().setPersonName(data.get(0).getIdcard().getName());
                                UserCenterCommon.getInstance().setNation(data.get(0).getIdcard().getNation());
                                String birthday = DateUtil.formatDate(data.get(0).getIdcard().getBirthday(), "yyyy-MM-dd HH:mm:ss");
                                UserCenterCommon.getInstance().setBirthday(birthday);
                                UserCenterCommon.getInstance().setIdCard(data.get(0).getIdcard().getIdCardNo());
                                UserCenterCommon.getInstance().setPersonSex(data.get(0).getIdcard().getSex());
                                UserCenterCommon.getInstance().setIdFront(data.get(0).getPath());
                                //继续传背面的照片
                                uploadPhoto(mBackList, Constant.URL_UPLOADS_IDCARDBACK);
                                mIsFirst = false;
                            } else {
                                mIsCutHead = true;
                                dismissProgressDialog();
                                DialogTools.getInstance().showCustomWarning(mActivity, mActivity.getResources().getString(R.string.identify_false),
                                        mActivity.getResources().getString(R.string.identify_false_reason), false, new DialogTools.ConfirmListener() {
                                            @Override
                                            public void setConfirmListener(Dialog dialog, View view, String s) {
                                                dialog.dismiss();
                                            }
                                        });
                            }

                        } else if (!mIsFirst && !mIsCutHead) {
                            dismissProgressDialog();
                            if (data.get(0).getIdcard() != null&&!TextUtils.isEmpty(data.get(0).getIdcard().getValidDate())) {
                                UserCenterCommon.getInstance().setExpirationDate(data.get(0).getIdcard().getValidDate());
                            } /*else {

                                DialogTools.getInstance().showCustomWarning(mActivity, mActivity.getResources().getString(R.string.identify_false),
                                        mActivity.getResources().getString(R.string.identify_false_reason), false, new DialogTools.ConfirmListener() {
                                            @Override
                                            public void setConfirmListener(Dialog dialog, View view, String s) {
                                                dialog.dismiss();
                                            }
                                        });
                            }*/
                            mIsCutHead = true;
                            mIsFirst = true;
                            UserCenterCommon.getInstance().setIdBack(data.get(0).getPath());
                            popFragment();
                            //身份证上传成功后跳转到下一步
                            pushFragment(new RCRealNameAuthStep2Fragment());

                        } else if (mIsCutHead) {
                            UserCenterCommon.getInstance().setIdHeader(data.get(0).getPath());
                            mIsCutHead = false;
                            uploadPhoto(mFrontList, Constant.URL_UPLOADS_IDCARDFRONT);
                        }
                    }
                } else {
                    dismissProgressDialog();
                    toast(mActivity.getResources().getString(R.string.up_faile));
                }

            }

            @Override
            public void onFailed(int what, FileUploadBean fileUploadBean) {
                LogUtils.showInfoLog("onFailed" + what);
                dismissProgressDialog();
                toast(mActivity.getResources().getString(R.string.up_faile));
            }
        });
    }
}
